import 'package:flutter/material.dart';
import 'package:bear_story/views.dart';
import '../main.dart';
import '../net.dart' as net;
import 'package:bear_story/dialog.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';

class UserNickNameSetPage extends StatelessWidget {
  final TextEditingController controller = TextEditingController();
  final user = getNowUser();

  void _doSubmit(BuildContext context) async {
    if (controller.text == null || controller.text.length == 0) {
      showToast("请输入昵称", context);
      return;
    }

    if (user == null) {
      return;
    }

    showLoadingDialog(context);
    net.updateUser(user.objectId, {"nickName": controller.text}).then((v) {
      Navigator.of(context).pop();
      if (v as bool) {
        user.nickName = controller.text;
        updateNowUser(user);
        showToast("设置成功", context);
        Navigator.of(context).pop();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    controller.text = user.nickName;
    return Scaffold(
      appBar: AppBar(
        title: Text("设置昵称"),
        backgroundColor: main_theme_color,
        centerTitle: true,
        elevation: 0,
        actions: <Widget>[
          GestureDetector(
            onTap: () {
              _doSubmit(context);
            },
            child: Container(
              width: 50.0,
              alignment: Alignment.center,
              child: new Text(
                '提交',
                style: TextStyle(fontSize: 16, color: Colors.white),
              ),
            ),
          ),
        ],
      ),
      body: Builder(builder: (context) {
        return Container(
          padding: EdgeInsets.only(top: 14),
          constraints: BoxConstraints.expand(),
          color: background_color,
          child: Column(
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(
                    left: main_padding_left, right: main_padding_left, top: main_padding_top, bottom: main_padding_top),
                color: Colors.white,
                child: TextField(
                  maxLines: 1,
                  controller: controller,
                  keyboardAppearance: Brightness.light,
                  style: TextStyle(fontSize: 15, fontWeight: FontWeight.w300, color: Color(0xff000000)),
                  decoration: InputDecoration(
                      labelText: "请输入昵称",
                      focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: main_theme_color)),
                      border: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffcbcbcb))),
                      enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffcbcbcb))),
                      labelStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.w300, color: Color(0xffb2b2b2))),
                ),
              ),
//              Padding(
//                padding: EdgeInsets.only(top: 20),
//              ),
//              Container(
//                padding: EdgeInsets.symmetric(horizontal: main_padding_left),
//                constraints: BoxConstraints.expand(height: 44),
//                child: FlatButton(
//                  onPressed: () {
//                    doSubmit(context);
//                  },
//                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(25))),
//                  color: Color(0xffff4d4d),
//                  child: Text(
//                    "提交",
//                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white),
//                  ),
//                ),
//              )
            ],
          ),
        );
      }),
    );
  }
}

class UserAgeSetPage extends StatelessWidget {
  final TextEditingController controller = TextEditingController();
  final user = getNowUser();

  void _doSubmit(BuildContext context) async {
    if (controller.text == null || controller.text.length == 0) {
      showToast("请输入年龄", context);
      return;
    }

    if (user == null) {
      return;
    }

    showLoadingDialog(context);
    int age = int.parse(controller.text);
    net.updateUser(user.objectId, {"age": age}).then((v) {
      Navigator.of(context).pop();
      if (v as bool) {
        user.age = age;
        updateNowUser(user);
        showToast("设置成功", context);
        Navigator.of(context).pop();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    controller.text = user.age.toString();
    return Scaffold(
      appBar: AppBar(
          title: Text("设置年龄"),
          backgroundColor: main_theme_color,
          centerTitle: true,
          elevation: 0,
          actions: <Widget>[
            GestureDetector(
              onTap: () {
                _doSubmit(context);
              },
              child: Container(
                width: 50.0,
                alignment: Alignment.center,
                child: new Text(
                  '提交',
                  style: TextStyle(fontSize: 16, color: Colors.white),
                ),
              ),
            ),
          ]),
      body: Builder(builder: (context) {
        return Container(
          padding: EdgeInsets.only(top: 14),
          constraints: BoxConstraints.expand(),
          color: background_color,
          child: Column(
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(
                    left: main_padding_left, right: main_padding_left, top: main_padding_top, bottom: main_padding_top),
                color: Colors.white,
                child: TextField(
                  maxLines: 1,
                  controller: controller,
                  keyboardType: TextInputType.number,
                  keyboardAppearance: Brightness.light,
                  style: TextStyle(fontSize: 15, fontWeight: FontWeight.w300, color: Color(0xff000000)),
                  decoration: InputDecoration(
                      labelText: "请输入年龄",
                      focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: main_theme_color)),
                      border: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffcbcbcb))),
                      enabledBorder: UnderlineInputBorder(borderSide: BorderSide(color: Color(0xffcbcbcb))),
                      labelStyle: TextStyle(fontSize: 14, fontWeight: FontWeight.w300, color: Color(0xffb2b2b2))),
                ),
              ),
//              Padding(
//                padding: EdgeInsets.only(top: 20),
//              ),
//              Container(
//                padding: EdgeInsets.symmetric(horizontal: main_padding_left),
//                constraints: BoxConstraints.expand(height: 44),
//                child: FlatButton(
//                  onPressed: () {
//                    doSubmit(context);
//                  },
//                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(25))),
//                  color: Color(0xffff4d4d),
//                  child: Text(
//                    "提交",
//                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white),
//                  ),
//                ),
//              )
            ],
          ),
        );
      }),
    );
  }
}

class UserSexSetPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _UserSexSetPageState();
  }
}

class _UserSexSetPageState extends State<UserSexSetPage> {
  final user = getNowUser();
  int groupValue = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    groupValue = user.sex;
  }

  void _updateGroupValue(int v) {
    setState(() {
      groupValue = v;
    });
  }

  void _doSubmit(BuildContext context) async {
    if (groupValue == 0) {
      showToast("请选择性别", context);
      return;
    }
    showLoadingDialog(context);
    net.updateUser(user.objectId, {"sex": groupValue}).then((v) {
      Navigator.of(context).pop();
      if (v as bool) {
        user.sex = groupValue;
        updateNowUser(user);
        showToast("设置成功", context);
        Navigator.of(context).pop();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
          title: Text("设置性别"),
          centerTitle: true,
          backgroundColor: main_theme_color,
          elevation: 0,
          actions: <Widget>[
            GestureDetector(
              onTap: () {
                _doSubmit(context);
              },
              child: Container(
                width: 50.0,
                alignment: Alignment.center,
                child: new Text(
                  '提交',
                  style: TextStyle(fontSize: 16, color: Colors.white),
                ),
              ),
            ),
          ]),
      body: Builder(builder: (context) {
        return Container(
          padding: EdgeInsets.only(top: 14),
          constraints: BoxConstraints.expand(),
          color: background_color,
          child: Column(
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(
                    left: main_padding_left, right: main_padding_left, top: main_padding_top, bottom: main_padding_top),
                color: Colors.white,
                child: Row(
                  children: <Widget>[
                    Radio(
                        value: 1,
                        groupValue: groupValue,
                        activeColor: main_theme_color,
                        onChanged: (v) {
                          _updateGroupValue(v);
                        }),
                    Text("男"),
                    Padding(padding: EdgeInsets.only(left: 16)),
                    Radio(
                        value: 2,
                        groupValue: groupValue,
                        activeColor: main_theme_color,
                        onChanged: (v) {
                          _updateGroupValue(v);
                        }),
                    Text("女"),
                  ],
                ),
              ),
//              Padding(
//                padding: EdgeInsets.only(top: 20),
//              ),
//              Container(
//                padding: EdgeInsets.symmetric(horizontal: main_padding_left),
//                constraints: BoxConstraints.expand(height: 44),
//                child: FlatButton(
//                  onPressed: () {
//                    doSubmit(context);
//                  },
//                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(25))),
//                  color: Color(0xffff4d4d),
//                  child: Text(
//                    "提交",
//                    style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: Colors.white),
//                  ),
//                ),
//              )
            ],
          ),
        );
      }),
    );
  }
}

class UserHeadUrlSetPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _UserHeadUrlSetPageState();
  }
}

class _UserHeadUrlSetPageState extends State<UserHeadUrlSetPage> {
  final user = getNowUser();
  File _image;

  Widget _getImgWidget() {
    if (_image != null) {
      return Container(
        width: 180,
        height: 180,
        child: ClipOval(
          child: Image.file(
            _image,
            fit: BoxFit.cover,
          ),
        ),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(90)),
            border: Border.all(color: Color(0xffcccccc), width: 2)),
      );
    } else if (user.headUrl == null || user.headUrl.length == 0) {
      return Container(
        width: 180,
        height: 180,
        child: ClipOval(
          child: Image.asset(
            "images/mrtx.png",
            fit: BoxFit.cover,
          ),
        ),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(90)),
            border: Border.all(color: Color(0xffcccccc), width: 2)),
      );
    } else {
      return Container(
        width: 180,
        height: 180,
        child: ClipOval(
          child: Image.network(
            user.headUrl,
            fit: BoxFit.cover,
          ),
        ),
        decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(90)),
            border: Border.all(color: Color(0xffcccccc), width: 2)),
      );
    }
  }

  void _selectImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    setState(() {
      _image = image;
    });
  }

  void _doSubmit(BuildContext context) async {
    if (_image == null) {
      showToast("请选择图片", context);
      return;
    }
    showLoadingDialog(context);
    var v1 = await net.uploadHeadImg(_image, "${user.objectId}_head.png");

    if (v1 == null || v1["url"] == null) {
      Navigator.of(context).pop();
      showToast("设置失败", context);
      return;
    }

    var v2 = await net.updateUser(user.objectId, {"headUrl": v1["url"], "headCdn": v1["cdn"]});
    if (!v2) {
      Navigator.of(context).pop();
      showToast("设置失败", context);
      return;
    }
    var v3 = await net.deleteHeadImg(user);
    if (!v3) {
      Navigator.of(context).pop();
      showToast("设置失败", context);
      return;
    }
    user.headUrl = v1["url"];
    user.headCdn = v1["cdn"];
    Navigator.of(context).pop();
    showToast("设置成功", context);
    Navigator.of(context).pop();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
          title: Text("设置头像"),
          backgroundColor: main_theme_color,
          elevation: 0,
          centerTitle: true,
          actions: <Widget>[
            GestureDetector(
              onTap: () {
                _doSubmit(context);
              },
              child: Container(
                width: 50.0,
                alignment: Alignment.center,
                child: new Text(
                  '提交',
                  style: TextStyle(fontSize: 16, color: Colors.white),
                ),
              ),
            ),
          ]),
      body: Builder(builder: (context) {
        return Container(
          padding: EdgeInsets.only(top: 14),
          constraints: BoxConstraints.expand(),
          color: background_color,
          child: Column(
            children: <Widget>[
              OutlineButton(
                onPressed: () {
                  _selectImage();
                },
                child: Text("选择图片"),
              ),
              Padding(
                padding: EdgeInsets.only(top: 12),
              ),
              _getImgWidget(),
            ],
          ),
        );
      }),
    );
  }
}
